package com.tfswx.fljdmxyy.validation;

import lombok.SneakyThrows;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.*;

/**
 * 取值范围校验，可为空
 *
 * @author root
 * @date 2022-02-21
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = ValueRange.Validator.class)
public @interface ValueRange {
    String[] value() default {};

    Class<? extends Enum<?>>[] enumType() default {};

    String message() default "{path}-值不正确，可选值：{value}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};


    class Validator implements ConstraintValidator<ValueRange, Object> {
        private final List<String> values = new ArrayList<>();

        @Override
        public void initialize(ValueRange constraintAnnotation) {
            values.addAll(Arrays.asList(constraintAnnotation.value()));
            Class<? extends Enum<?>>[] classes = constraintAnnotation.enumType();
            if (classes.length > 0) {
                for (Enum<?> enumConstant : classes[0].getEnumConstants()) {
                    values.add(enumConstant.name());
                }
            }
        }

        @SneakyThrows
        @Override
        public boolean isValid(Object value, ConstraintValidatorContext context) {
            if (value == null) {
                return true;
            }
            String s = value.toString();
            for (String value1 : values) {
                if (s.equals(value1)) {
                    return true;
                }
            }
            Map<String, Object> v = new HashMap<>();
            v.put("vaule", values);
            ValidUtil.setParam(context, v);
            return false;
        }
    }
}
